/*
 * Copyright 2013 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.tngou.db.netty.http;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

public class HttpServerHandler extends ChannelInboundHandlerAdapter {
    private static byte[] CONTENT = { 'T', 'n', 'g', 'o', 'u', ' ', 'D', 'B' };
    

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	Map<String, String> requestParams=new HashMap<>();
    	if (msg instanceof HttpRequest) {  //GET请求       
        	HttpRequest req = (HttpRequest) msg; 
        	if(req.method().equals(HttpMethod.GET)){
	            String uri=req.uri();
	            requestParams=_requestParams(requestParams, uri);
				try {uri = URLDecoder.decode(req.uri(), "utf-8");
				} catch (UnsupportedEncodingException e) {	TngouHttpUtil.run_404(ctx);return ;}
	            if(uri.startsWith("/query"))
	            {
	            	QueryAction action = new QueryAction();
	            	action.execute(ctx,requestParams);
	            	return;
	            }
	            if(uri.startsWith("/sysinfo"))
	            {
	            	QueryAction action = new QueryAction();
	            	action.sysinfo(ctx);
	            	return;
	            }
	            String webroot=SystemUtils.getUserDir()+File.separator+"WebRoot";
	            File file= new File(webroot+uri);
	            if(file.isDirectory())file=new File(webroot+uri+"index.html");
	            if(!file.isFile())
	            {
	            	TngouHttpUtil.run_404(ctx);return ;
	            }else
	            {
	            	try {
						CONTENT=FileUtils.readFileToByteArray(file);
					} catch (IOException e) {
						TngouHttpUtil.run_404(ctx);return ;
					}
	            }
	             TngouHttpUtil.run(ctx, req, CONTENT);          
	             return ;
        	}
        }  
        if (msg instanceof HttpContent) {//POST参数
    		 HttpContent content = (HttpContent) msg;
 	   		 ByteBuf buf = content.content();
 	         String uri = buf.toString(io.netty.util.CharsetUtil.UTF_8);
 	         if(StringUtils.isNoneBlank(uri))
 	         {
	 	         if(StringUtils.isNoneBlank(uri)){
	 	        	 requestParams=_requestParams(requestParams, "?"+uri);
	 	         }   	 	       
	 	        QueryAction action = new QueryAction();
	 	        action.execute(ctx,requestParams);
 	         }   
    	}
        
      
        
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    
    
    private Map<String, String> _requestParams(Map<String, String> map ,String uri) {
    	QueryStringDecoder decoder = new QueryStringDecoder(uri);  
        Map<String, List<String>> parame = decoder.parameters();  
        Iterator<Entry<String, List<String>>> iterator = parame.entrySet().iterator();
        while(iterator.hasNext()){
            Entry<String, List<String>> next = iterator.next();
            map.put(next.getKey(), next.getValue().get(0));
        }
        return map;
	}
    
    
}
